#include "ajax_handler.h"
#include <settings/config_parser.h>
#include <settings/system_settings.h>

namespace webconfig {
Json::Value GetJsonDataCenter(const Json::Value &param)
{
    settings::ConfigParser configParser;
    Json::Value baseConfig;
    std::vector<settings::ConfigParser::DataCenter> dataCenters = configParser.GetDataCenter();

    for (settings::ConfigParser::DataCenter dc : dataCenters) {
        Json::Value jsonDc;
        jsonDc["id"] = dc.ID;
        jsonDc["host"] = dc.host;
        jsonDc["port"] = dc.port;
        jsonDc["secretKey"] = dc.key;
        jsonDc["tls"] = dc.isTls ? 1 : 0;
        baseConfig.append(jsonDc);
    }
    return baseConfig;
}

Json::Value GetJsonNetworkInfo(const Json::Value &param)
{
    settings::SystemSettings sysSettings;
    sysSettings.UpdateNetDev();
    Json::Value netJson;
    for (settings::SystemSettings::NetCard &netCard : sysSettings.netCards) {
        Json::Value netJ;
        netJ["ip"] = netCard.ipAddr;
        netJ["mac"] = netCard.MAC;
        netJ["name"] = netCard.ifname;
        netJ["gateway"] = netCard.gateway;
        netJ["netmask"] = netCard.mask;
        netJ["model"] = false;
        netJson.append(netJ);
    }
    return netJson;
}

Json::Value GetJsonDiskInfo(const Json::Value &param)
{
    Json::Value diskJson;
    settings::SystemSettings sysSettings;
    sysSettings.UpdateDiskInfo();
    char disk[20], mem[20];
    sprintf(disk, "%d M/%d M", sysSettings.freeDiskSpace, sysSettings.totalDiskSpace);
    sprintf(mem, "%d M/%d M", sysSettings.freeMemory, sysSettings.totalMemory);
    diskJson["free"] = sysSettings.freeDiskSpace;
    diskJson["total"] = sysSettings.totalDiskSpace;
    return diskJson;
}

Json::Value GetJsonMemInfo(const Json::Value &param)
{
    settings::SystemSettings sysSettings;
    sysSettings.UpdateMemInfo();
    Json::Value memJson;
    memJson["free"] = sysSettings.freeMemory;
    memJson["total"] = sysSettings.totalMemory;
    return memJson;
}

Json::Value GetJsonSysInfo(const Json::Value &param)
{
    settings::SystemSettings sysSettings;
    sysSettings.UpdateSysInfo();
    Json::Value sysJson;
    sysJson["version"] = sysSettings.appVer;
    sysJson["time"] = sysSettings.sysTime;
    sysJson["upgradeTime"] = sysSettings.upgradeTime;
    sysJson["updateConfigTime"] = sysSettings.updateConfigTime;
    return sysJson;
}

Json::Value GetJsonGatewayInfo(const Json::Value &param)
{
    Json::Value result;
    result["disk"] = GetJsonDiskInfo();
    result["memory"] = GetJsonMemInfo();

    result["network"] = GetJsonNetworkInfo();
    result["system"] = GetJsonSysInfo();
    return result;
}

} // namespace webconfig